/**
 *  @author phi
 *  @memo   
 */

#include "game-app-manager.h"
#include <gl/glut.h>

namespace {

    void timer(int value)
    {
        theGameAppManager.update();

        glutPostRedisplay();
        glutTimerFunc(theGameAppManager.fps(), timer, 0);
    }

    void disp()
    {
        glClear(GL_COLOR_BUFFER_BIT);

        theGameAppManager.draw();

        glutSwapBuffers();
        tmlib::theKeyInfo.flags(0);
    }

}

void GameAppManager::initialize(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitWindowPosition(200, 200);
    glutInitWindowSize(640, 480);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);

    glutCreateWindow("TMLib");
    glutTimerFunc(fps(), timer, 0);   // update
    glutDisplayFunc(disp);              // draw

    glutMouseFunc(tmlib::MouseInfo::onMouseUpdate);
    glutMotionFunc(tmlib::MouseInfo::onMouseUpdate);
    glutPassiveMotionFunc(tmlib::MouseInfo::onMouseUpdate);
    glutSpecialFunc(tmlib::KeyInfo::onKeyUpdate);

    glOrtho(0, 640, 480, 0, 0, 1);

    tmlib::KeyInfoHolder::create();
    tmlib::MouseInfoHolder::create();

    _app->initialize();
}

void GameAppManager::finalize()
{
    _app->finalize();
    delete _app;

    tmlib::KeyInfoHolder::destroy();
    tmlib::MouseInfoHolder::destroy();
}

void GameAppManager::run()
{
    glutMainLoop();
}

void GameAppManager::update()
{
    _app->update();
}

void GameAppManager::draw()
{
    _app->draw();
}
